package com.tuanzi.loan.web.configuration.asyn;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@EnableAsync
@Configuration
public class AsynConfiguration implements AsyncConfigurer {

	@Autowired
	private TaskExecutor taskExecutor;

	@Override
	public Executor getAsyncExecutor() {
		return taskExecutor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}

	@Bean
	public TaskExecutor taskExecutor(TaskExecutorProperties properties) {
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
		pool.setCorePoolSize(properties.getCorePoolSize());
		pool.setMaxPoolSize(properties.getMaxPoolSize());
		pool.setKeepAliveSeconds(properties.getKeepAliveSeconds());
		pool.setQueueCapacity(properties.getQueueCapacity());
		pool.setThreadNamePrefix(properties.getThreadNamePrefix());
		pool.setWaitForTasksToCompleteOnShutdown(properties.getWaitForTasksToCompleteOnShutdown());
		pool.initialize();
		return pool;
	}

}
